import plotly
import getdatah
import pandas as pd
import matplotlib.pyplot as plt
from flask import Flask, redirect, render_template, request
import plotly.graph_objs as go
import pandas as pd
import io
import base64
import plotly.express as px
from flask import Flask, render_template, request, jsonify
import pandas as pd
import pre
import numpy as np
from flask import Flask, send_file
import io
import datetime
import matplotlib.font_manager as fm
import json
import plotly.graph_objs as go


app = Flask(__name__)

@app.route('/visual', methods=['GET', 'POST'])
def visualize():
    global df
    if request.method == 'POST':
        column_name = request.form['column_name']
        chart_type = request.form['chart_type']
        if chart_type == 'line':
            fig = px.line(df, x=df.index, y=column_name, title=f'{column_name} Trend')
        elif chart_type == 'bar':
            fig = px.bar(df, x=df.index, y=column_name, title=f'{column_name} Distribution')
        elif chart_type == 'scatter':
            fig = px.scatter(df, x=df.index, y=column_name, title=f'{column_name} Scatter Plot')
        elif chart_type == 'pie':
            fig = px.pie(df, values=column_name, names=df.index, title=f'{column_name} pie Chart')
        
        plot_data = fig.to_json()
        return jsonify({'plotData': plot_data, 'title': fig.layout.title.text})
    
    cityname = request.args.get('cityname')
    df = getdatah.translate_column_names(cityname)
    columns = list(df.columns)
    return render_template('index.html', columns=columns)

@app.route('/prewea', methods=['GET', 'POST'])
def prewea():
    if request.method == 'POST':
        cityname = request.form['cityname']
        year = int(request.form['year'])
        epochs = int(request.form['epochs'])
        days = int(request.form['days'])
        result_df = pre.pre_data(cityname, year, epochs,days)

        # 创建一个折线图
        trace1 = go.Scatter(x=result_df['日期'], y=result_df['最高温'], mode='lines', name='最高温')
        trace2 = go.Scatter(x=result_df['日期'], y=result_df['最低温'], mode='lines', name='最低温')
        # 设置图表布局
        layout = go.Layout(title=f'{cityname}未来{days}天天气预测', xaxis=dict(title='日期'), yaxis=dict(title='温度'))

        # 将图表数据和布局组合成一个字典
        fig = go.Figure(data=[trace1, trace2], layout=layout)

        # 将图表转换为JSON对象
        fig_json = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)

        return render_template('result.html', fig_json=fig_json)

    else:
        current_cityname = request.args.get('cityname', "")
        return render_template('home.html', current_cityname=current_cityname)
    

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000,debug=True)